//
//  JsonUtil.swift
//  WorkDemo
//
//  Created by 韩云智 on 2019/9/25.
//  Copyright © 2019 韩云智. All rights reserved.
//
//  模型转换工具(应用泛型)

import Foundation
import HandyJSON

open class JsonUtil {
    /**
     *  Json转对象
     */
    public static func jsonToModel<T:HandyJSON>(_ jsonStr:String,_ modelType:T.Type) ->T {
        if jsonStr == "" || jsonStr.count == 0 {
            #if DEBUG
            print("jsonoModel:字符串为空")
            #endif
            return modelType.init()
        }
        return (modelType.deserialize(from: jsonStr))!
    }
    
    /**
     *  Json转数组对象
     */
    public static func jsonArrayToModel<T:HandyJSON>(_ jsonArrayStr:String, _ modelType:T.Type) ->[T] {
        if jsonArrayStr == "" || jsonArrayStr.count == 0 {
            #if DEBUG
            print("jsonToModelArray:字符串为空")
            #endif
            return []
        }
        var modelArray:[T] = []
        let data = jsonArrayStr.data(using: .utf8)
        let peoplesArray = try! JSONSerialization.jsonObject(with:data!, options: JSONSerialization.ReadingOptions()) as? [AnyObject]
        for people in peoplesArray! {
            modelArray.append(dictionaryToModel(people as! [String : Any], modelType))
        }
        return modelArray
        
    }
    
    /**
     *  字典转对象
     */
    public static func dictionaryToModel<T:HandyJSON>(_ dictionStr:[String:Any],_ modelType:T.Type) -> T {
        if dictionStr.count == 0 {
            #if DEBUG
            print("dictionaryToModel:字符串为空")
            #endif
            return modelType.init()
        }
        return (modelType.deserialize(from: dictionStr))!
    }
    public static func arrayToModel<T:HandyJSON>(_ array:[[String:Any]],_ modelType:T.Type) -> [T] {
        if array.count == 0 {
            #if DEBUG
            print("dictionaryToModel:字符串为空")
            #endif
            return []
        }
        var modelArray:[T] = []
        for dic in array {
            modelArray.append(dictionaryToModel(dic, T.self))
        }
        return modelArray
    }
    
    /**
     *  对象转JSON
     */
    public static func modelToJson(_ model:HandyJSON?) -> String {
        if model == nil {
            #if DEBUG
            print("modelToJson:model为空")
            #endif
            return ""
        }
        return (model?.toJSONString())!
    }
    
    /**
     *  对象转字典
     */
    public static func modelToDictionary(_ model:HandyJSON?) -> [String:Any] {
        if model == nil {
            #if DEBUG
            print("modelToJson:model为空")
            #endif
            return [:]
        }
        return (model?.toJSON())!
    }
}
